var cusContactsTable = function() {
	return {
		init : function() {
			var validator;
			var tableId = "cus_contacts_table";
			//初始化checkBox 初始化行点击选中
			util.initCheckBox(tableId);
			function queryData(sSource, aoData, fnCallback) {
				aoData.push({
					"name" : "empName",
					"value" : $("#id_empName").val().trim()
				});
				aoData.push({
					"name" : "ownerComp",
					"value" : $("#id_ownerComp").val()
				});
				aoData.push({
					"name" : "ownerFactory",
					"value" : $("#id_ownerFactory").val()
				});
				$.ajax({
					"type" : "post",
					"url" : sSource,
					"dataType" : "json",
					"data" : {
						"aoData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						fnCallback(resp);
					}
				});
			};
			$('#cus_contacts_table').DataTable({
				"processing" : true,
				"serverSide" : true,
				"sAjaxSource" : "main/cusContacts/getCusContacts.mvc",
				"fnServerData" : queryData,
				"pageLength" : 10,
				"sDom" : "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
				"oLanguage" : util.getDToLanguage(),
				"columns" : [ {
					"data" : "pkId",
					"render" : function(data, type, full, meta) {
						 return '<div class="checker" onclick="util.selectCheckBox(\'' + tableId + '\', this)"><span><input type="checkbox" class="checkboxes"/></span></div>';
					},
					"bSortable" : false
				},
				{
					"data" : "empName",
					"bSortable" : false
				}, 
				{
					"data" : "sexStr",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "job",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "phone",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "email",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "cusName",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "parentCusName",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "facName",
					"bSortable" : false,
					"defaultContent": ""
				}],
				"fnDrawCallback" : function(oSetting) {
					util.clearSelected(tableId);
				}
			});
			
			$("#form_ownerComp").change(function(e) {
				var cusId = $(this).children('option:selected').val();
				$.ajax({
					"type" : "post",
					"url" : "main/customer/getCustomerById.mvc",
					"dataType" : "json",
					"data" : {
						"pkId" : cusId
					},
					"success" : function(data) {
						if(data){
							//$("#parentCusId").val(data.parentCusId);
							$("#form_parentCus").val(data.parentCusName);
						}
					}
				}); 
			});
			//窗口关闭时重置内容
			$("#form_btn_close , .close").click(function(e) {
				$("#form_contactId").val("");
				$("#contact_form")[0].reset();
				if(validator) {
					$("#contact_form").validate().resetForm();
				}
				$("#form_ownerFactory").find("option").not(":first").remove();
			});
			
			// 查询
			$("#btn_query").click(function(e) {
				var table = $('#cus_contacts_table').DataTable();
				table.draw(true);
			});
		    // 重置
			$("#btn_reset").click(function(e) {
				$("#contact_search_form")[0].reset();
				$(".select2-selection__rendered").empty();
				$(".select2-selection__rendered").append("<span class='select2-selection__placeholder'>请选择</span>");
			});
			
			//新增
			$("#emp_add").click(function(e){
				$('#addContact_title').text('新增客户人员');
				util.getDictByParentKey("SYS_XBDM", 'form_sex', null);
				util.getOption("main/cusContacts/getCustomers.mvc", null, "form_ownerComp");
				$("#add_contact").modal({show:true,keyboard:false});
			});
			
			// 修改
			$('#emp_edit').on('click', function(e) {
				var d = [];
				d = util.getCheckedData("cus_contacts_table");
				if (d.length != 1) {
					util.showModal("#_alertModal", "请选择一条记录进行操作！");
					return false;
				}
				$('#addContact_title').text('编辑客户人员');
				var table = $('#cus_contacts_table').DataTable();
				util.getDictByParentKey("SYS_XBDM", 'form_sex', null);
				util.getOption("main/cusContacts/getCustomers.mvc", null, "form_ownerComp");
				$("#add_contact").modal({show:true,keyboard:false});
				$.ajax({
					"type" : "post",
					"url" : "main/cusContacts/getContactInfo.mvc",
					"dataType" : "json",
					"data" : {
						"pkId" : d[0].pkId
					},
					"success" : function(resp) {
						var contact = resp.data;
						$("#form_contactId").val(contact.pkId);
						$("#form_empName").val(contact.empName);
						$("#form_sex").val(contact.sex);
						$("#form_job").val(contact.job);
						$("#form_phone").val(contact.phone);
						$("#form_email").val(contact.email);
						$("#form_ownerComp").val(contact.ownerComp);
						$("#form_ownerComp").change();
						$("#form_ownerFactory").val(contact.ownerFactory);
					}
				});
			});
			
			//删除
			$("#emp_delete").on('click', function(){
				var d = [];
				d = util.getCheckedData("cus_contacts_table");
				if (d.length == 0) {
					util.showModal("#_alertModal", "请选择要操作的记录！");
				} else {
					util.showModal("#_confirmModal", "您确定要删除选中记录？", "_confirmModal_yes");
				}
			});
			
			$("#_confirmModal").on('click', '#_confirmModal_yes', function() {
				var d = [];
				d = util.getCheckedData("cus_contacts_table");
				var idArray=[];
				for (var i=0;i<d.length;i++) {
					idArray.push(d[i].pkId);
				}
				var table = $('#cus_contacts_table').DataTable();
				$.ajax({
					"type" : "post",
					"url" : "main/cusContacts/delete.mvc",
					"dataType" : "json",
					"data" : {
						"pkId" : idArray.join(",")
					},
					"success" : function(resp) {
						if (resp.msg==true) {
							rmsBox.notify('success', {msg: '删除成功！'});
							table.draw(true);
						} else if (resp.msg=='bind') {
							util.showModal("#_alertModal", "用户已绑定账号，需解除绑定才可删除！");
						}
					}
				});
			});
			
			$(function(){
				//查询区域下拉框赋值
				util.getOption("main/cusContacts/getCustomers.mvc", null, "id_ownerComp");
				util.getOption("main/cusContacts/getFactory.mvc", null, "id_ownerFactory");
				$('#form_ownerComp').bind('change', function(){
					var customId;
					customId = $('#form_ownerComp').val();
					var param = {};
					param["customId"]=customId;
					$("#form_ownerFactory").find("option").not(":first").remove();
					util.getOption("main/cusContacts/getFactory.mvc", param, "form_ownerFactory");
			    });
				//初始化所属客户下拉框
				$("#id_ownerFactory, #id_ownerComp").select2({
	          	     placeholder:'全部',//默认文字提示
	          	     language: "zh-CN",//汉化
	          	     allowClear: true//允许清空
	          	});
				$("#form_ownerComp,#form_ownerFactory").select2({
	          	     placeholder:'请选择',//默认文字提示
	          	     language: "zh-CN",//汉化
	          	     allowClear: true//允许清空
	          	});
				
				$('.search-body .my-input').bind('keyup', function(event) {
					if (event.keyCode == "13") {
						//回车执行查询
						$('.search-button #btn_query').click();
					}
				});
			});
			
			//保存
			$("#form_contact_save").click(function(){
				validator = validateMyForm("contact_form");
				if(!validator.form()) {
					return false;
				}
				var data = {};
				data['pkId'] = $("#form_contactId").val();
				data['empName'] = $("#form_empName").val();
				data['sex'] = $("#form_sex").val();
				data['job'] = $("#form_job").val();
				data['phone'] = $("#form_phone").val();
				data['email'] = $("#form_email").val();
				data['ownerComp'] = $("#form_ownerComp").val();
				data['ownerFactory'] = $("#form_ownerFactory").val();
				var table = $('#cus_contacts_table').DataTable();
				$.ajax({
					"type" : "post",
					"url" : "main/cusContacts/saveOrUpdateContact.mvc",
					"dataType" : "json",
					"data" : data,
					"success" : function(resp) {
						$("#form_btn_close").click();
						rmsBox.notify('success', {msg: '保存成功！'});
						table.draw(true);
					},
					"error" : function(resp) {
						rmsBox.notify('error', {msg: '保存失败！',delay:3000});
					}
				});
			});
			function validateMyForm(formId){
				return $( '#' + formId ).validate({
					errorElement: 'em',
					//errorClass: 'redStar',
					focusInvalid: false, 
					ignore: "",
					rules:{  
						empName:{
							'required':true
						},
						sex:'required',
						job:'required',
						phone:{
							'required':true,
							checkPhone:true
						},
						email:{
							'required':true,
							'email':true
						},
						ownerComp : {
							'required' : true
						},
						ownerFactory : {
							'required' : true
						}
					},
					messages:{  
						empName:{
							required :'不能为空'
						},
						sex:'请选择性别',
						job:'不能为空',
						phone:{
							required:'不能为空',
							checkPhone:'号码格式错误'
						},
						email:{
							required:'不能为空',
							email:'邮箱格式错误'
						},
						ownerComp:{
							required:'不能为空'
						},
						ownerFactory:{
							required:'不能为空'
						}
					}, 
					errorPlacement: function (error, element) { 
						//默认以span形式显示在输入框后
						error.insertAfter(element);
						$(element.next()).attr('title', $(error).text()).tooltip();
						$(error).text('');
					}
				});
			}
			$.validator.addMethod("checkPhone",function(value,element,params){  
				var checkPhone = /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/;
				return this.optional(element)||(checkPhone.test(value));
			},"号码格式错误");  
		}
	};
}();
